<template>
  <div class="NavigationBar">
    <el-tabs
      v-model="editableTabsValue"
      type="card"
      :closable="editableTabs.length > 1"
      @tab-remove="removeTab"
      @tab-click="clickTab"
    >
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
      >
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  data() {
    return {
      editableTabsValue: "0",
      editableTabs: [],
    };
  },
  methods: {
    // 点击删除的（X）
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter((tab) => tab.name !== targetName);
      const path = tabs.filter((tab) => tab.name === this.editableTabsValue)[0].path;
      this.$route.path == path || this.$router.push(path)
    },
    // 点击tab
    clickTab(targetName) {
      const path = this.editableTabs[targetName.index].path
      this.$route.path == path || this.$router.push(path)
    },
  },
  watch: {
    $route: {
      handler(to) {
        const isExist = this.editableTabs.some((item) => {
          return item.path === to.path;
        });
        // 如果跳转的路由已存在当前栈
        if (isExist) {
          this.editableTabsValue =
            this.editableTabs.indexOf(
              this.editableTabs.filter((item) => {
                if (item.path === to.path) return item.path === to.path;
              })[0]
            ) + "";
        } else {
          this.editableTabs.push({
            path: to.path,
            title: to.meta.title,
            name: this.editableTabs.length + "",
          });
          this.editableTabsValue = this.editableTabs.length - 1 + "";
        }
      },
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.NavigationBar {
  width: 100%;
  border-top: 1px solid #e4e7ed;
}
</style>
<style lang="scss">
.NavigationBar {
  .el-tabs {
    .el-tabs__header {
      margin: 0;
    }
    .el-tabs__content {
      display: none;
    }
    .el-tabs__item {
      height: 30px;
      line-height: 30px;
    }
    .el-tabs__nav-prev {
      height: 30px;
      line-height: 30px;
    }
    .el-tabs__nav-next {
      height: 30px;
      line-height: 30px;
    }
    .el-tabs__nav {
      border-top: none !important;
    }
    .el-tabs__item.is-top.is-active{
      background-color: #41b88310;
    }
  }
}
</style>